import cv2
import numpy as np

base_size = 300  # short size
crop_size = 299
mean_value = np.array([128.0, 128.0, 128.0])  # BGR
std = np.array([128.0, 128.0, 128.0])  # BGR


def image_preprocess(img):
    b, g, r = cv2.split(img)
    return cv2.merge([(b - mean_value[0]) / std[0], (g - mean_value[1]) / std[1], (r - mean_value[2]) / std[2]])


def center_crop(img):
    # single crop
    short_edge = min(img.shape[:2])
    if short_edge < crop_size:
        return
    yy = int((img.shape[0] - crop_size) / 2)
    xx = int((img.shape[1] - crop_size) / 2)
    return img[yy: yy + crop_size, xx: xx + crop_size]


def one_image_preprosessing(img_path):
    img = cv2.imread(img_path)
    img = cv2.resize(img, (int(img.shape[1] * base_size / min(img.shape[:2])),
                           int(img.shape[0] * base_size / min(img.shape[:2]))))
    img = image_preprocess(img)
    img = center_crop(img)
    img = np.asarray(img).transpose((2, 0, 1))
    img = np.expand_dims(img, axis=0)
    return img
